<template>
  <div class="collection-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="收藏" fixed placeholder/>

    <!-- 主选项卡 - 使用 Vant 的 tabs 组件 -->
    <van-tabs v-model:active="mainActive" class="main-tabs">
      <!-- 第一个标签页：我的收藏 -->
      <van-tab title="我的收藏" name="collection">
        <!-- 自定义子选项卡 - 替代 Vant 的 tabs 实现更灵活的样式 -->
        <div class="custom-sub-tabs">
          <div v-for="tab in subTabs" :key="tab.name" class="custom-sub-tab"
            :class="{ 'active': subActive === tab.name }" @click="subActive = tab.name">
            {{ tab.title }}
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="content">
          <!-- 菜谱收藏内容 -->
          <div v-if="subActive === 'recipe'">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading">
              <van-loading size="24px">加载中...</van-loading>
            </div>
            <!-- 空状态 -->
            <div v-else-if="!collectedRecipes.length" class="empty">
              <van-empty image="search" description="暂无收藏菜谱" />
            </div>
            <!-- 菜谱列表 -->
            <div v-else class="list">
              <!-- 每个收藏的菜谱项 -->
              <div v-for="item in collectedRecipes" :key="item.recipeId" class="item" @click="handleItemClick(item)">
                <div class="item-left">
                  <img width="100%" height="100%" fit="cover" :src=item.imageUrl :alt="item.title" />
                </div>
                <div class="item-right">
                  <!-- 菜谱标题 -->
                  <div class="title van-ellipsis">{{ item.title }}</div>
                  <!-- 菜谱描述 -->
                  <div class="description van-ellipsis">
                    {{ item.description || '暂无描述' }}
                  </div>
                  <!-- 元信息：作者和分类 -->
                  <!-- <div class="meta-info">
                    <span class="author">{{ item.authorName }}</span>
                    <span class="categories" v-if="item.categories.length">
                      {{ item.categories.join(' | ') }}
                    </span>
                  </div> -->
                  <!-- 收藏数 -->
                  <div class="collect-count">
                    <van-icon name="star" color="#ff976a" />
                    <span>{{ item.collectCount }}人收藏</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 视频收藏内容 -->
          <div v-if="subActive === 'video'">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading">
              <van-loading size="24px">加载中...</van-loading>
            </div>
            <!-- 空状态 -->
            <div v-else-if="!collectedVideos.length" class="empty">
              <van-empty image="search" description="暂无收藏视频" />
            </div>
            <!-- 视频列表 -->
            <div v-else class="video-list">
              <div v-for="video in collectedVideos" :key="video.favoriteId" class="video-item">
                <video width="100%" controls preload="metadata">
                  <source :src="video.videoUrl" type="video/mp4">
                  您的浏览器不支持视频播放
                </video>
                <div class="video-info">
                  <div class="video-meta">
                    <!-- <span>视频ID: {{ video.videoId }}</span> -->
                    <span class="collect-count">
                      <van-icon name="star" color="#ff976a" />
                      <span>{{ video.collectCount }}人收藏</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </van-tab>

      <!-- 第二个标签页：我的点赞 -->
      <van-tab title="我的点赞" name="like">
        <div class="empty">
          <van-empty description="暂无点赞内容" />
        </div>
      </van-tab>
    </van-tabs>

  </div>
</template>

<script setup>
// 导入 Vue 相关功能
import { ref, watch, onMounted, computed } from 'vue';
// 导入 API 方法
import {
  getFavoriteAll,
  getRecommendRecipeAll,
  getCuisineCategoriesAll,
  getUserAll,
  getFavoriteVideosAll
} from '../api';
// 导入 Pinia 存储
import { useUserInfoStore } from '../stores/userInfo';
// 导入 Vant 组件
import { showToast } from 'vant';
// 导入路由
import { useRouter } from 'vue-router';

const router = useRouter()


// 使用 Pinia 存储
const userInfoStore = useUserInfoStore();

// 定义测试用户 - 这里设置用户ID为1，与数据库一致
// const setupTestUser = () => {
//   userInfoStore.userInfo = {
//     userId: 1,
//     username: '测试用户'
//   };
//   // console.log('测试用户已设置:', userInfoStore.userInfo);
// };

// 定义响应式状态
const mainActive = ref('collection');
const subTabs = [
  { title: '菜谱', name: 'recipe' },
  { title: '视频', name: 'video' }
];
const subActive = ref('recipe');
const loading = ref(false);

// 数据源
const favorites = ref([]);
const allRecipes = ref([]);
const categories = ref([]);
const users = ref([]);
const favoriteVideos = ref([]);

// 调试用 - 打印关键数据
const debugData = () => {
  // console.log('当前用户:', userInfoStore.userInfo);
  // console.log('数据库中所有收藏记录:', favorites.value);
  // console.log('所有菜谱:', allRecipes.value);
  // console.log('计算后的收藏菜谱:', collectedRecipes.value);
};

// 计算属性 - 获取当前用户收藏的菜谱
const collectedRecipes = computed(() => {
  if (!userInfoStore.userId) {
    // console.log('无用户ID，返回空数组');
    return [];
  }

  // 获取当前用户的所有收藏记录
  const userFavorites = favorites.value.filter(
    item => item.userId === userInfoStore.userId
  );

  // console.log("userInfoStore",userInfoStore);
  // console.log('用户收藏记录:', userFavorites);

  // 获取收藏对应的菜谱并添加额外信息
  const result = allRecipes.value
    .filter(recipe => {
      const isCollected = userFavorites.some(fav => fav.recipeId === recipe.recipeId);
      // console.log(`菜谱 ${recipe.recipeId} 是否被收藏:`, isCollected);
      return isCollected;
    })
    .map(recipe => {
      // 添加分类信息
      const recipeCategories = categories.value
        .filter(cat => cat.recipeId === recipe.recipeId)
        .map(cat => cat.catagoryName);

      // 添加作者信息
      const author = users.value.find(user => user.userId === recipe.userId) || {};

      return {
        ...recipe,
        categories: recipeCategories,
        authorName: author.username || '未知用户',
        // 计算收藏数
        collectCount: favorites.value.filter(fav => fav.recipeId === recipe.recipeId).length
      };
    });

  // console.log('最终收藏菜谱结果:', result);
  return result;
});

// 计算属性 - 获取当前用户收藏的视频（带收藏量）
const collectedVideos = computed(() => {
  if (!userInfoStore.userId || !favoriteVideos.value.length) {
    return [];
  }

  // 1. 先计算每个视频的总收藏量
  const videoCollectCounts = {};
  favoriteVideos.value.forEach(video => {
    if (!videoCollectCounts[video.videoId]) {
      videoCollectCounts[video.videoId] = 0;
    }
    videoCollectCounts[video.videoId]++;
  });

  // 2. 获取当前用户收藏的视频（去重）
  const userVideoIds = new Set();
  const userVideos = favoriteVideos.value.filter(video => {
    if (video.userId === userInfoStore.userId && !userVideoIds.has(video.videoId)) {
      userVideoIds.add(video.videoId);
      return true;
    }
    return false;
  });

  // 3. 合并数据
  return userVideos.map(video => ({
    ...video,
    collectCount: videoCollectCounts[video.videoId] || 0
  }));
});

// 获取所有基础数据
const fetchAllData = async () => {
  try {
    loading.value = true;
    // console.log('开始获取数据...');

    // 并行请求所有数据，解构赋值 
    const [favoritesRes, recipesRes, categoriesRes, usersRes, favoriteVideosRes] = await Promise.all([
      getFavoriteAll(),
      getRecommendRecipeAll(),
      getCuisineCategoriesAll(),
      getUserAll(),
      getFavoriteVideosAll()
    ]);

    // console.log("@@@@", recipesRes);
    // console.log('API返回数据:', { favoritesRes, recipesRes, categoriesRes, usersRes });

    // 赋值响应式数据，判断是否为数组
    favorites.value = Array.isArray(favoritesRes) ? favoritesRes : [];
    allRecipes.value = Array.isArray(recipesRes) ? recipesRes : [];
    categories.value = Array.isArray(categoriesRes) ? categoriesRes : [];
    users.value = Array.isArray(usersRes) ? usersRes : [];
    favoriteVideos.value = Array.isArray(favoriteVideosRes) ? favoriteVideosRes : [];

    // showToast('数据加载成功');
    debugData(); // 打印调试信息
  } catch (error) {
    console.error('获取数据失败:', error);
    //showToast的作用：页面会alert一个提示信息
    showToast('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 处理菜谱点击 - 跳转到详情页
const handleItemClick = (item) => {
  //跳转至详细页
  router.push({
    name: 'recipe_datail',
    query: { recipeId: item.recipeId }
  })
  // console.log('查看菜谱详情:', item);
};


// 监听用户信息变化
watch(() => userInfoStore, (newVal) => {
  // console.log('用户信息变化:', newVal);
  if (newVal.userId) {
    fetchAllData();
  }
}, { immediate: true });

// 组件挂载时执行
onMounted(() => {
  // console.log('组件挂载');
  if (userInfoStore.userId) {
    fetchAllData();
  } else {
    console.error('用户ID未设置，无法获取收藏数据');
  }
});

</script>

<style scoped>
/* 或者使用Vant自带的省略号类 */
.van-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.collection-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 主选项卡样式 - 保持原生但去除下划线 */
.main-tabs :deep(.van-tabs__line) {
  display: none;
}

.main-tabs :deep(.van-tab) {
  font-size: 16px;
  color: #969799;
}

.main-tabs :deep(.van-tab--active) {
  color: #323233;
  font-weight: 500;
}

/* 自定义子选项卡按钮样式 */
.custom-sub-tabs {
  display: flex;
  justify-content: center;
  padding: 8px 16px;
  background-color: #fff;
}

.custom-sub-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #969799;
  padding: 6px 0;
  margin: 0 8px;
  border: 1px solid #ebedf0;
  border-radius: 16px;
  background-color: #f7f8fa;
  transition: all 0.3s;
}

.custom-sub-tab.active {
  color: #ee0a24;
  background-color: #fff;
  border-color: #ee0a24;
  box-shadow: 0 2px 8px rgba(238, 10, 36, 0.1);
}

/* 内容区域 */
.content {
  flex: 1;
  overflow: auto;
  padding: 0 12px;
}

/* 列表样式 */
.list {
  padding: 10px 0;
}

.item {
  display: flex;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-left {
  width: 55%;
  height: 100px;
}

.item-right {
  width: 45%;
  padding: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.description {
  flex: 1;
  font-size: 13px;
  color: #666;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 4px;
}

.collect-count {
  font-size: 12px;
  color: #ff976a;
  display: flex;
  align-items: center;
}

.collect-count span {
  margin-left: 4px;
}

.loading,
.empty {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* meta样式 */
/* .meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 4px 0;
  font-size: 12px;
  color: #969799;
}

.meta-info span {
  display: inline-block;
} */

/* .categories {
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
} */

/* video */
.video-list {
  padding: 10px 0;
}

.video-item {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background: #fff;
  transition: transform 0.3s ease;
}

.video-item:hover {
  transform: translateY(-2px);
}

.video-item video {
  display: block;
  background: #000;
  border-radius: 8px 8px 0 0;
}

/* 视频信息区域 - 可以添加标题等信息 */
.video-info {
  padding: 10px 12px;
}

.video-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 6px;
  color: #323233;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #969799;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .video-item {
    margin-bottom: 12px;
  }

  .video-info {
    padding: 8px 10px;
  }

  .video-title {
    font-size: 14px;
    margin-bottom: 4px;
  }
}

/* 在style部分添加 */
.video-meta .collect-count {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #ff976a;
}

.video-meta .collect-count span {
  margin-left: 4px;
}
</style>